<?php 
	include($_SERVER['DOCUMENT_ROOT']."/headerins.php");
?>

<?php

try
{
	
	if($_GET["action"] == "product"){

		$result = mysql_query("SELECT name FROM material where code = '" . $_GET['code'] . "'");
		
		//Add all records to an array
		$rows = array();
		while($row = mysql_fetch_array($result))
		{
		    $rows[] = $row;
		}

		$jTableResult = array();
		$jTableResult['Result'] = "OK";
		$jTableResult['Records'] = $rows;
		print json_encode($jTableResult);
	}
	else if($_GET["action"] == "create")
	{
		//Insert record into database
		$sql = "
			INSERT INTO `order` 
				(UserId, UserIdTo, CreateDT, Description) 
            VALUES(
				'" . $_SESSION['userID'] . "', 
				'" . $_GET["userIDTo"] . "', 
				'" . date('Y-m-d', strtotime(str_replace('-', '/',$_GET["createDT"]))) . "',  
				'" . $_GET["Description"] . "'
            );
                              ";

			$result = mysql_query($sql);
		if (!$result) {
		    die('Order/update/sql: ' . mysql_error(). $sql);
		}else{
			$jTableResult = array();
			$sql = 'SELECT ID FROM `order` WHERE ID = LAST_INSERT_ID()';
			$result = mysql_query($sql);
			while($row = mysql_fetch_array($result)){
				$jTableResult['Result'] = "OK";
				$jTableResult['LastID'] = $row['ID'];
				print json_encode($jTableResult);
			}
		}
            //print('Order/update/sql: successfull.');
	}
	//Updating a record (updateAction)
	else if($_GET["action"] == "update")
	{
		//Update record in database
		$result = mysql_query("UPDATE `order` SET  
				UserIDTo = '" . $_GET["userIDTo"] . "',
				Description = '" . $_GET["Description"] . "',
				CreateDT = '" . date('Y-m-d', strtotime(str_replace('-', '/',$_GET["createDT"]))) . "'
                                WHERE Id = " . $_GET["ID"] . ";");
        if (!$result) {
            die('Order/update/sql: ' . mysql_error(). $sql);
        }else{
				$jTableResult['Result'] = "OK";
				print json_encode($jTableResult);
		}
				
	}
	//Deleting a record (deleteAction)
	else if($_GET["action"] == "delete")
	{
		//Delete from database
		$result = mysql_query("DELETE FROM `order` WHERE Id = " . $_GET["ID"] . ";");
		$result = mysql_query("DELETE FROM orderLine WHERE OrderId = " . $_GET["ID"] . ";");

        if (!$result) {
            die('Order/delete/sql: ' . mysql_error(). $sql);
        }else
            print('Order/delete/sql: successfull.');
	}

	//Close database connection
	mysql_close($con);

}
catch(Exception $ex)
{
	 echo mysql_error();
}
	
?>
